package com.wangsh.train.web.head.intercepor;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSONObject;
import com.wangsh.train.common.controller.BaseController;
import com.wangsh.train.common.pojo.ApiResponse;
import com.wangsh.train.common.pojo.ApiResponseEnum;
import com.wangsh.train.common.pojo.JSONEnum;
import com.wangsh.train.common.util.ConstatFinalUtil;
import com.wangsh.train.outer.IClientOuterService;
import com.wangsh.train.users.pojo.AUsers;
import com.wangsh.train.users.service.IUsersDbService;

/**
 * 配置拦截器
 * @author Xh-Win10-Server
 */
@Component("authHeadInterceptor")
public class AuthHeadInterceptor extends BaseController implements HandlerInterceptor
{
	/* 管理员的登录网址 */
	private String loginUrl = ConstatFinalUtil.CONFIG_JSON.getString("usersCenter.head.login.url") ; 
	@Resource
	private IClientOuterService clientOuterService;
	
	@Resource
	private IUsersDbService usersDbService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		ConstatFinalUtil.SYS_LOGGER.info("--preHandle--");
		
		/* 设置一些公共的变量 */
		this.commonOper(request);
		
		HttpSession session = request.getSession();
		AUsers users = (AUsers) session.getAttribute("users");
		
		if(users != null)
		{
			return true ; 
		}
		
		//ConstatFinalUtil.SYS_LOG.info("----1 preHandle(执行之后执行) ----");
		String[] tokens = request.getParameterValues("token");
		String token = "" ; 
		if(tokens != null && tokens.length > 0)
		{
			token = tokens[tokens.length - 1]; 
		}
		
		/* 存储数据信息 */
		JSONObject dataReqJSON = new JSONObject();
		try
		{
			if (users == null && !"".equalsIgnoreCase(token))
			{
				dataReqJSON.put("token", token);
				/* 验证管理员的token */
				JSONObject responseJSON = this.clientOuterService.verifyUsersTokenService(dataReqJSON);
				
				if(responseJSON != null && responseJSON.getInteger("code") == ApiResponseEnum.STATUS_SUCCESS.getStatus())
				{
					//登陆成功
					JSONObject dataJSON = (JSONObject) responseJSON.get("data");
					JSONObject usersJSON = dataJSON.getJSONObject("users");
					String id = usersJSON.get("id") + "";
					String email = usersJSON.get("email") + "";
					String nickName = "";
					String trueName = "";
					String lastLoginTime = usersJSON.get("lastLoginTime") + "";
					/* 判断字符串 */
					if(usersJSON.get("nickName") != null)
					{
						nickName = usersJSON.get("nickName") + "" ;
					}
					if(usersJSON.get("trueName") != null)
					{
						trueName = usersJSON.get("trueName") + "" ;
					}
					
					Map<String, Object> condMap = new HashMap<String, Object>();
					condMap.put("ssoId", id);
					ApiResponse<AUsers> adminsResponse = this.usersDbService.findOneUsersService(condMap);
					users = adminsResponse.getDataOneJava() ; 
					
					if(users != null)
					{
						users.setEmail(email);
						users.setNickName(nickName);
						users.setTrueName(trueName);
						users.setSsoId(Integer.valueOf(id));
						users.setUpdateTime(new Date());
						users.setLastLoginTime(this.dateFormatUtil.strDateTime(lastLoginTime));
						//将令牌放到对象之中
						users.setTokenStr(token);
						
						this.usersDbService.updateOneUsersService(users);
					}else
					{
						users = new AUsers();
						users.setEmail(email);
						users.setNickName(nickName);
						users.setTrueName(trueName);
						users.setSsoId(Integer.valueOf(id));
						users.setStatus(Byte.valueOf("1"));
						users.setCreateTime(new Date());
						users.setUpdateTime(new Date());
						users.setLastLoginTime(this.dateFormatUtil.strDateTime(lastLoginTime));
						//将令牌放到对象之中
						users.setTokenStr(token);
						
						ApiResponse<Object> apiResponse = this.usersDbService.saveOneUsersService(users);
						if(apiResponse.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus() )
						{
							Map<String,Object> dataOneMap = apiResponse.getDataOne(); 
							users.setId(Integer.valueOf(dataOneMap.get(JSONEnum.ID.getName()) + ""));
						}
					}
					
					session.setAttribute("users", users);
					return true ; 
				}
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("请求服务器报错了:{}", dataReqJSON, e);
		}
		
		/* 加上returnUrl */
		String returnUrl = request.getRequestURL() + "";
		String queryStr = request.getQueryString() ;
		if(queryStr == null)
		{
			queryStr = "" ; 
		}
		returnUrl += "?" + queryStr ; 
		
		/* 对ReturnUrl进行encode加密 */
		String returnUrlEncode = URLEncoder.encode(returnUrl, "UTF-8");
		
		ConstatFinalUtil.SYS_LOGGER.info("---returnUrl:{}--returnUrlEncode:{}",returnUrl,returnUrlEncode);
		String loginUrl = this.loginUrl + "&returnUrl=" + returnUrlEncode ; 
		response.sendRedirect(loginUrl);
		return false;
	}
}
